/**
 * type: 产品
 * des：长城汇数据获取
 * by: Xie Xiaofei
 * created: 2017/5/27
 * lastupdate: 2017/7/7
 * 
 */



var path = require('path')
var url = path.basename(__filename, '.js')
var SqlHelper = require('../utils/sql.js')
var schedule = require('node-schedule')
var clearRedundantField = require('../utils/clearRedundantField.js')
var dateHelper = require('../utils/date.js')
var User = require('./cch_user.js')
var jsonWebToken = require('../utils/jwt.js');
var dataCleaner = require('./dataCleaner.js');
var dataCleanerQs = require('./dataCleaner_qs.js')
/*  zb.zxkjy	紫昕科技园
    zb.csxm	测试项目
    zb.03	长城汇
    zb.02	青山健吾假日广场
    zb.01	光谷天地
    zb.01.01	光谷天地一期
    zb.01.02	光谷天地二期
    zb.04	锦绣龙城
 */

const projMap = [
    'zb.03',      // 长城汇
    'zb.01.01',    // 光谷天地1期
    'zb.01.02',    // 光谷天地2期
    'zb.02', // 青山健吾
    'zb.04', // 锦绣龙城
    null, // 达尚城
    null // 湖北高铁新城
]

var freshData = () => {
    console.log(dateHelper.now() + '正在拉取长城汇数据...')
    var sql = new SqlHelper('cch_building_data');
    sql.query('DELETE from cch_building_data', null, function (results) {
        for (let i = 0; i < projMap.length; i++) {
            fetchRemoteRoomData(projMap[i]);
        }
    })
}

var fetchRemoteRoomData = (projCode) => {

    if (!projCode) return;

    // console.log(dateHelper.now() + '   Starting fetch remote data...')

    var soap = require('soap');
    var url = 'http://58.49.121.242:8160/CCTZERPSERVICES.asmx?wsdl';
    var sql = new SqlHelper('cch_building_data');
    soap.createClient(url, function (err, client) {
        client.GetRoomData({ 'projCode': projCode }, function (err, result) {
            if (err) {
                console.log(err);
                return;
            }
            var data = result.GetRoomDataResult;
            if (typeof (data) == "string") {
                let jsonData = JSON.parse(data);
                // 清理数据格式

                if (projCode === 'zb.04') {
                    dataCleaner.jxlcDataCleaner(jsonData)
                }

                if (projCode === 'zb.02') {
                    dataCleanerQs.jxlcDataCleaner(jsonData)
                }

                sql.insertSet(jsonData, function (results) {
                    console.log(dateHelper.now() + '  fetch data success.' + projCode)
                })

            }
        });
    });
}

// 每天的23:59刷新数据
var j = schedule.scheduleJob('59 23 * * *', function () {
    freshData();
});
freshData();
/**
 * 获取长城汇的数据
 */

const projNameMap = {
    'cch': '长城汇',
    'ggtd1': '光谷天地一期',
    'ggtd2': '光谷天地二期',
    'jwjr': '青山健吾假日广场',
    'jxlc': '锦绣龙城',
    'dsc': '达尚城',
    'dwgtxc': '大悟高铁新城'
}

var getCCHData = (projName, res) => {

    var where = { 'projName': projNameMap[projName] };
    var sql = new SqlHelper('cch_building_data');

    sql.select(where, (results) => {
        // 根据不同楼栋分组
        for (let i = 0; i < results.length; i++) {
            delete results[i].RoomGUID;
            delete results[i].RoomShortInfo;
            delete results[i].ProjName;

            // 消除单元问题，单元直接在楼层显示
            // if (results[i].Unit || results[i].Unit != "") {
            //     results[i].Floor = results[i].Unit + '-' + results[i].Floor;
            // }
            delete results[i].Unit;

            // 遍历对象，空值直接删除属性
            for (let j in results[i]) {
                if (results[i][j] && results[i][j] != "") {
                    continue;
                } else {
                    delete results[i][j];
                }
            }
        }

        var buildingAr = clearRedundantField(results, 'BldFullName');

        for (let i = 0; i < buildingAr.length; i++) {
            buildingAr[i].data = clearRedundantField(buildingAr[i].data, 'Floor');;
        }
        res.setHeader('Cache-Control', 'max-age=60');
        console.log(dateHelper.now() + '  Feched  ' + projNameMap[projName]);
        return res.send(buildingAr)
    })

}


// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  长城汇各类户型信息 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

var getData = function (req, res) {

    // 参数验证
    var projName = req.params.projName || req.query.projName;
    if (!projName) {
        return res.send({ code: 0, data: '参数错误' })
    }

    // Token验证
    var clientToken = req.header('Authorization');
    if (!clientToken) {
        return res.send({ code: 0, data: "无权限" });
    }

    jsonWebToken.decode(clientToken)
        .then((tokenData) => {
            var userData = {
                userid: tokenData.userid
            }
            var sqlHelper = new SqlHelper('cch_user');
            return sqlHelper.asyncSelect(userData);
        })
        .then((results) => {
            if (results.length > 0) {
                // 验证权限
                if (results[0][projName] > 0) {
                    return getCCHData(projName, res);
                }
                return res.send({ code: 0, data: '无项目数据' });
            } else {
                return res.send({ code: 0, data: '无权限' });
            }
        })
        .catch((data) => {     // 错误处理
            console.log(data);
            return res.send(data);
        })
}



// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  长城汇登陆 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓


var login = function (req, res) {

    var params = req.params;

    if (!params.userid || !params.userpw) {
        return res.send({ code: 0, msg: '参数错误 !' });
    }

    var data = {
        userid: params.userid,
        userpw: params.userpw
    }
    var user = new User(data);
    user.select()
        .then((results) => {
            if (results.length > 0) {  // 登陆成功
                jsonWebToken.encode(results[0].userid)
                    .then(function (token) { // Token授权
                        delete results[0].userid;
                        delete results[0].userpw;
                        return res.send({ code: 1, token: token, userInfo: results[0] });
                    })
            } else {
                return res.send({ code: 0, data: '密码或账户错误' });
            }
        })
        .catch((err) => {
            console.log(err);
        })
}





// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  长城汇账号管理 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓


var authotable = function (req, res) {
    var params = req.params;

    // 命令解析
    var cmd = req.params.cmd;
    delete req.params.cmd;

    // 定义对象
    var user = new User(req.params)

    switch (cmd) {
        case 'delete':
            user.delete().then((results) => {
                if (results.affectedRows > 0) {
                    return res.send({ code: 1 })
                }
            })
            break;
        case 'update':
            user.update().then((results) => {
                if (results.affectedRows > 0) {
                    return res.send({ code: 1 })
                }
            })
            break;

        case 'add':
            user.add().then((results) => {
                if (results.affectedRows > 0) {
                    return res.send({ code: 1 })
                }
            })
            break;
        case 'list':
            user.selectAll().then((results) => {
                return res.send({ code: 1, data: results })
            })
            break;
        case 'comments':
            user.comments().then((results) => {
                return res.send({ code: 1, data: results })
            })
            break;
        case 'count':
            user.count().then((results) => {
                return res.send({ code: 1, data: results })
            })
            break;
        case 'mix':
            let comments = null;
            let list = null;
            user.comments().then((results) => {
                comments = results;
                return user.selectAll();
            }).then((results2) => {
                list = results2;
                return res.send({ code: 1, data: { comments: comments, list: list } });
            })
            break;
        default:
            res.send({ code: 0, data: '参数错误' });
    }

}


/**
 * 长城汇登陆
 * url: /cchlogin
 * method: post
 * params: userid, userpw
 * return: { code: 1, token: token, userInfo: results[0] }
 */

/**
* 长城汇登陆Token刷新 (暂时不做此功能)
* url: /cchfresh
* method: post
* params: token
* return: { code: 1, token: token}
*/

/** 
 * 长城汇各类户型信息
 * url: /cch
 * method: get
 * params: projName(cch/ggtd1/...)
 * return: []
*/

/** 
 * 用户信息操作
 * url: /cch/authotable
 * method: post
 * params: cmd,userid,userpw,...
 * return: []
*/


server.post('/cch/authotable', authotable)
server.post('/cch', login)
server.get('/cch', getData)
